package logic

import (
	"context"
	"github.com/mojocn/base64Captcha"
	"strings"

	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"

	"github.com/zeromicro/go-zero/core/logx"
)

var (
	// store 全局captcha缓存
	store = base64Captcha.DefaultMemStore
)

// Captcha 生成图片的结构体
type Captcha struct {
	id     string
	b64s   string
	answer string
}

type CaptchaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CaptchaLogic {
	return &CaptchaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CaptchaLogic) Captcha(in *transform.CaptchaReq) (*transform.CaptchaResp, error) {
	// 1. 检查验证码类型，作为扩展，默认0即可
	// 2. 随机生成验证码图片
	captcha, err := generateCaptcha()
	if err != nil {
		return nil, err
	}
	_ = store.Set(captcha.id, captcha.answer)
	return &transform.CaptchaResp{
		Key:   captcha.id,
		Image: captcha.b64s,
	}, nil
}

// generateCaptcha 生成验证码图片
func generateCaptcha() (*Captcha, error) {
	// NewDriverString 高/宽/背景噪点数量/干扰线数量/验证码长度/验证码随机文本/背景色/字体
	driverString := base64Captcha.NewDriverString(60, 100, 50, 2, 4, "123456abcdefghijklmnopqrstuvwxyz", nil, nil, nil)
	id, b64s, ans, err := base64Captcha.NewCaptcha(driverString, store).Generate()
	if err != nil {
		return nil, err
	}
	return &Captcha{
		id:     id,
		b64s:   b64s,
		answer: strings.ToUpper(ans),
	}, nil
}

// VerifyCaptcha 校验验证码
func VerifyCaptcha(key, code string) bool {
	code = strings.ToUpper(code)
	return store.Verify(key, code, true)
}
